﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;
using System.Threading;
using log4net.Config;
using log4net.Core;
using log4net.Appender;
using log4net.Layout;
using log4net.Repository.Hierarchy;

namespace Ooganizer.Server
{
    public class LogServer
    {
        public LogServer(string logFilePath, string sinkName)
        {
            // TODO - should take level as parameter to LogServer
            startLogServer(logFilePath, sinkName, Level.All);
        }

        ~LogServer()
        {

        }

        private void startLogServer(string logFilePath, string sinkName, Level level)
        {
            // Configure remoting
            TcpServerChannel channel = new TcpServerChannel(8085);
            ChannelServices.RegisterChannel(channel, false);

            // Publish the remote logging server. This is done using the log4net plugin.
            log4net.LogManager.GetRepository().PluginMap.Add(new log4net.Plugin.RemoteLoggingServerPlugin(sinkName));

            if (logFilePath != null)
            {
                BasicConfigurator.Configure(LogServer.createRollingFileAppender(logFilePath, level));
            }
        }

        static private FileAppender createFileAppender(string logFilePath, Level level)
        {
            FileAppender fileAppender = new FileAppender();
            fileAppender.Layout = new PatternLayout(PatternLayout.DetailConversionPattern);
            fileAppender.File = logFilePath;
            fileAppender.AppendToFile = true;
            fileAppender.Threshold = level;

            fileAppender.ActivateOptions();

            return fileAppender;
        }

        static private RollingFileAppender createRollingFileAppender(string logFilePath, Level level)
        {            
            RollingFileAppender fileAppender = new RollingFileAppender();
            fileAppender.Layout = new PatternLayout(PatternLayout.DetailConversionPattern);
            fileAppender.File = logFilePath;
            fileAppender.AppendToFile = true;
            fileAppender.Threshold = level;
            fileAppender.MaximumFileSize = "10MB";
            fileAppender.MaxSizeRollBackups = 3;

            fileAppender.ActivateOptions();

            return fileAppender;
        }

        // Create a logger
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
    }
}
